import path, { resolve } from 'path';
import { assign } from '@borderless/assign';
import { defineConfig, UserConfig } from 'vite';

import vue from '@vitejs/plugin-vue';
import rollupPluginReplace from '../../plugins/rollup/replace';

function projectRoot(dir: string) {
    return path.join(__dirname, '..', '..', '..', dir);
}

function srcRoot(dir: string) {
    return path.join(__dirname, '..', '..', dir);
}

// 基础构建
function getBaseConfig(): UserConfig {
    return {
        root: '.',
        base: '',

        css: {
            postcss: './postcss.config.js',
        },

        resolve: {
            alias: {
                '~common': srcRoot('common'),
                '~service': srcRoot('service'),
                '~component': srcRoot('component'),
                '~original': projectRoot('original'),
            },
        },

        build: {
            reportCompressedSize: false,
            chunkSizeWarningLimit: 1024,
            terserOptions: {
                keep_classnames: true,
            },

            outDir: '../../../dist/renderer/nota',

            rollupOptions: {
                input: {
                    app: resolve(__dirname, 'index.html'),
                },

                external: ['~sqlite'],

                plugins: [
                    rollupPluginReplace({
                        values: {
                            '~sqlite': '../../sqlite/index.js',
                        },
                    }),
                ],
            },
        },

        optimizeDeps: {
            exclude: ['~sqlite'],
        },

        plugins: [vue()],
    };
}

export default defineConfig(({ mode }) => {
    // ...
    const baseConfig = getBaseConfig();

    switch (mode) {
        // 生产模式
        case 'production':
            return assign(baseConfig, {
                build: {
                    // FIX - warnings when minifying css
                    minify: false,
                },
            }) as UserConfig;

        // 开发模式
        default:
            return assign(baseConfig, {
                build: {
                    sourcemap: true,
                    watch: {}, // 监听

                    minify: false,
                    terserOptions: {
                        compress: false,
                    },
                },
            }) as UserConfig;
    }
});
